import { checkLogin } from '@/api/my'

// 检查token是否过期
export const checkTokenExpired = async () => {
  try {
    const token = uni.getStorageSync('token')
    if (!token) {
      handleLogout()
      return false
    }

    const res = await checkLogin()
    if (res.statusCode === 200) {
      const { code, info, data } = res.data

      if (code === 200) {
        return true
      } else {
        handleLogout()
        return false
      }
    } else {
      handleLogout()
      return false
    }
  } catch (error) {
    handleLogout()
    return false
  }
}

// 处理登出逻辑
const handleLogout = () => {
  // 清除本地存储
  uni.removeStorageSync('token')
  uni.removeStorageSync('userInfo')

  // 显示提示
  uni.showToast({
    title: '登录已过期，请重新登录',
    icon: 'none',
    duration: 2000,
  })

  // 延迟跳转到登录页
  setTimeout(() => {
    uni.reLaunch({
      url: '/pages/login/login',
    })
  }, 1500)
}
